from django.contrib import admin
from django.conf import settings
from django.apps import apps
from .models import Article, Topic, Subject, Category, Tag, Keyword, FriendLink


@admin.register(Subject)
class SubjectAdmin(admin.ModelAdmin):
    date_hierarchy = 'create_time'
    list_display = ('id', 'name', 'create_time', 'update_time', 'sort_order', 'status')
    list_editable = ('sort_order', 'status')
    list_display_links = ('name',)
    search_fields = ('create_time', 'status', 'sort_order')


@admin.register(Topic)
class TopicAdmin(admin.ModelAdmin):
    date_hierarchy = 'create_time'
    list_display = ('id', '__str__', 'create_time', 'update_time', 'sort_order', 'subject')
    list_editable = ('sort_order', )
    list_display_links = ('__str__',)
    list_fields = ('create_time', 'sort_order', 'subject')
    search_fields = ('name', 'subject__name')


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    date_hierarchy = 'create_time'
    list_display = ('id', 'title', 'is_top', 'is_published', 'topic', 'topic_order', 'topic_short_title', 'views')

    # 字段归类显示
    fieldsets = (
        ('文章信息', {
            'fields': (('title', 'slug'), 'body', 'summary', ('is_top', 'is_published'))
        }),
        ('文章关系信息', {
            'fields': ('author', 'category', 'tags', 'keywords')
        }),
        ('专题信息', {
            'fields': (('topic', 'topic_order'), 'topic_short_title')
        })
    )

    # 编辑字段
    list_editable = ('is_top', 'is_published', 'topic', 'topic_order', 'topic_short_title')

    list_display_links = ('title',)

    list_filter = ('is_published', 'create_time', 'author', 'category', 'is_top', 'topic', 'topic_order')

    list_per_page = 50

    filter_horizontal = ('tags', 'keywords')

    search_fields = ('title', 'author__username', 'category__name', 'topic__name', 'topic_short_title')

    def get_queryset(self, request):
        """重写get_queryset方法，限制用户权限，只能看到自己的文章"""
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """重写formfield_for_foreignkey方法，限制用户权限"""
        User = apps.get_model(settings.AUTH_USER_MODEL)
        if db_field.name == 'author':
            if request.user.is_superuser:
                kwargs['queryset'] = User.objects.filter(is_staff=True, is_active=True)
            else:
                kwargs['queryset'] = User.objects.filter(id=request.user.id)
        return super(ArticleAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'slug')


@ admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'slug')


@admin.register(Keyword)
class KeywordAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')


@admin.register(FriendLink)
class FriendLinkAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'link', 'is_active')
    date_hierarchy = 'create_time'
    list_filter = ('is_active',)
    list_editable = ('is_active', )
